#!/bin/sh
## 压缩日志文件脚本
isClr=0
isDel=0

# 帮助说明
function help(){
	echo "
		usage: [-c -d -h file]
 		 -c clear可选   压缩后清空文件
  		 -d delete可选  压缩后删除文件
		 -h help  获取指令运行帮助
		 
		 file  需要操作的文件名称,可带路径名称
		 
		 eg: tarlog -cd file  // 压缩文件file后清空并删除文件file
	"
}
	


# 获取长命令行
while getopts ":cdh" opt; do
                case $opt in
                        c)
                                isClr=1
                                ;;
                        d)
                                isDel=1
                                ;;
                        h)
                                help
                                exit 0
                                ;;
                        *)
                                echo -e "未知参数 $opt ！！！\n"
				help
                                exit 1
                                ;;
                esac
done


if [ $? != 0 ]; then
	echo "执行函数失败!!!"
	exit 1
fi

# 将位置参数移到已经处理过的选项之后
shift $(( OPTIND - 1 ))

if [ $# -lt 1 ]
then    
        echo " 请输入压缩文件名称!!! " 
	help
   	exit 1	
fi

for file in  $@ ; do 
	if [ ! -f $file  ];then
		echo "输入文件$file不存在！！！"
		exit 1
	fi	
done


for  file in  $@ ; do 
	base_name=$( basename $file )
	echo "开始日志 $file 的压缩..."
	echo "command: tar -zcvf  $base_name.tar.gz $base_name"
	tar -zcvf  $base_name.tar.gz  $base_name
	
	if [ $? != 0 ]; then
		echo "执行压缩日志文件$file失败!!!"
		exit 1
	fi

	echo "日志$file压缩成功"
	
	
if [ $isClr == 1 ];then
	echo "选择了压缩后清空日志文件$file,开始清空日志文件..."
	echo "command: echo '' > $file"
	echo "" > "$file"

	if [ $? != 0 ]; then
		echo "执行清空日志文件$file失败!!!"
		exit 1
	fi

	echo "清空日志文件$file成功"

fi 


if [ $isDel == 1 ];then 
	echo "选择了压缩后删除日志文件$file,开始删除日志文件..."
	echo "command: rm $file"
	rm $file

	if [ $? != 0 ]; then
		echo "执行删除日志文件$file失败!!!"
		exit 1
	fi

	echo "删除日志文件$file成功"

fi

done

echo "操作完成!!!!!"
exit 0

## 以下逻辑已屏蔽
:<< !
base_name=$( basename "$1" )
echo "开始日志 $1 的压缩..."
echo "command: tar -zcvf  $base_name.tar.gz $base_name"
tar -zcvf  $base_name.tar.gz  $base_name

if [ $? != 0 ]; then
	echo "执行压缩日志文件失败!!!"
	exit 1
fi

echo "日志压缩成功"

if [ $isClr == 1 ];then 
	echo "选择了压缩后清空日志文件$1,开始清空日志文件..."
	echo "" > $1

	if [ $? != 0 ]; then
		echo "执行清空日志文件$1失败!!!"
		exit 1
	fi

	echo "清空日志文件$1成功"

fi 


if [ $isDel == 1 ];then 
	echo "选择了压缩后删除日志文件$1,开始删除日志文件..."
	rm $1

	if [ $? != 0 ]; then
		echo "执行删除日志文件$1失败!!!"
		exit 1
	fi

	echo "删除日志文件$1成功"

fi 

echo "操作成功!!!"
!

## 已屏蔽以下逻辑
:<<!
if [ $? != 0 ]
then
	echo "执行压缩失败"
	exit 1

fi

if [ $# -eq 2 ] && [ $2 == 1 ]
then    
        echo " 选择了清空日志文件，开始清空日志文件... "
        echo "" > $1

	if [ $? != 0 ]
	then
        	echo "执行清空日志失败"
        	exit 1
	fi

fi

if [ $# -eq 3 ] && [ $2 == 1 ] && [ $3 == 1]
then
        echo " 选择了清空并删除日志文件$1，开始清空并删除日志文件... "
 
        echo "" > $1
	if [ $? != 0 ]
	then
        	echo "执行清空日志失败"
        	exit 1
	fi
 
	rm $1

	if [ $? != 0 ]
	then
        	echo "执行删除文件失败"
        	exit 1
	fi
fi

echo "操作成功!!!"
!
